package main

import (
	"crypto/tls"
	"crypto/x509"
	"fmt"
	"io/ioutil"
	"log"
	"net"
	"net/http"
	"time"
)

func main() {
	fmt.Println("Hello BuGuai !!! ")
	server()
}

func server() {

	buf, err := ioutil.ReadFile("./cert/bugai_root.pem")
	if err != nil {
		log.Fatalln(err)
	}

	pool := x509.NewCertPool()
	pool.AppendCertsFromPEM(buf)

	// cert, err := tls.LoadX509KeyPair("./cert/server.pem", "./cert/key.pem")
	// if err != nil {
	// 	log.Fatalln(err)
	// }

	http.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) {
		rw.Write([]byte(`{"msg":"ok"}`))
	})

	server := http.Server{
		Addr: ":443",
		TLSConfig: &tls.Config{
			// Certificates: []tls.Certificate{cert},
			ClientAuth: tls.RequireAndVerifyClientCert,
			ClientCAs:  pool,
		},
	}
	log.Fatal(server.ListenAndServeTLS("./cert/server.pem", "./cert/key.pem"))

}

func client() {
	// buf, err := ioutil.ReadFile("./cert/bugai_root.pem")
	// if err != nil {
	// 	log.Fatalln(err)
	// }

	// pool := x509.NewCertPool()
	// pool.AppendCertsFromPEM(buf)

	cert, err := tls.LoadX509KeyPair("./cert/client.pem", "./cert/key.pem")
	if err != nil {
		log.Fatalln(err)
	}

	http.DefaultTransport = &http.Transport{
		Proxy: http.ProxyFromEnvironment,
		DialContext: (&net.Dialer{
			Timeout:   30 * time.Second,
			KeepAlive: 30 * time.Second,
		}).DialContext,
		ForceAttemptHTTP2:     true,
		MaxIdleConns:          100,
		IdleConnTimeout:       90 * time.Second,
		TLSHandshakeTimeout:   10 * time.Second,
		ExpectContinueTimeout: 1 * time.Second,
		TLSClientConfig: &tls.Config{
			InsecureSkipVerify: true,
			Certificates:       []tls.Certificate{cert},
			// ClientCAs:          pool,
		},
	}

	r, err := http.Get("https://localhost")
	if err != nil {
		log.Fatalln(err)
	}
	defer r.Body.Close()

	b, err := ioutil.ReadAll(r.Body)
	if err != nil {
		log.Fatalln(err)
	}
	log.Println(string(b))
}
